<template>
  <view class="playDet">
    <!-- 背景 -->
    <view
      class="bgImg"
      :style="{ background: 'url(' + MusicDet.coverImgUrl + ')' }"
    ></view>
    <view class="bg"></view>
    <!-- 头部杠杆 -->
    <view :class="paly ? 'Bar playBar' : 'Bar'">
      <image src="@/static/img/player_bar.png" mode="" />
    </view>
    <!-- 光碟 -->
    <view class="CD">
      <image
        :class="paly ? ' disc rotate' : 'disc'"
        src="@/static/img/disc.png"
        mode=""
      />
      <image
        :class="paly ? 'img rotate' : 'img'"
        :src="MusicDet.coverImgUrl"
        mode=""
      />
      <!-- 播放 -->
      <view
        class="play iconfont icon-bofang"
        v-if="!paly"
        @click="isPalyC"
      ></view>
      <!-- 暂停 -->
      <view class="pause iconfont icon-step" v-else @click="isPalyC"></view>
    </view>
    <!-- 歌词 -->
    <view class="lyric">
      <scroll-view class="scroll" scroll-y :scroll-top="scrollindex">
        <view
          v-for="(item, index) in lrcObject"
          :key="index"
          :style="{ color: lyricIndex === index ? '#0DBC79' : '#fafafa' }"
          >{{ item.c }}</view
        >
      </scroll-view>
    </view>
    <!-- 相似歌曲 -->
    <view class="similarSong">
      <!-- 标题 -->
      <view class="similarTop appFlex-one">
        <view class="topLeft">喜欢听这首歌的人也听</view>
        <view class="topRight" @click="allListen">
          <text class="iconfont icon-bofang"></text>
          <text>一键收听</text>
        </view>
      </view>
      <!-- 相似歌曲列表 -->
      <view class="similarList">
        <view
          class="similarItem appFlex-one"
          v-for="(item, index) in MusicSimilar"
          :key="index"
          @click="playSimilarMusic(item)"
        >
          <view class="ItemLeft appFlex-one">
            <image class="similarImg" :src="item.album.blurPicUrl" mode="" />
            <view class="songAndname">
              <view class="song">{{ item.name }}</view>
              <view class="name"
                >{{ item.artists[0].name }}-{{ item.name }}</view
              >
            </view>
          </view>
          <view class="iconfont icon-bofang rightIcon"></view>
        </view>
      </view>
    </view>
    <!-- 精彩评论 -->
    <view class="comment">
      <view class="commTop">精彩评论</view>
      <!-- 评论列表 -->
      <view class="commentList">
        <view
          class="commentItem"
          v-for="(item, index) in MusicComment"
          :key="index"
        >
          <view class="user appFlex-one">
            <view class="userLeft appFlex-one">
              <image :src="item.user.avatarUrl" mode="" />
              <view class="nameAndTime">
                <view class="name">{{ item.user.nickname }}</view>
                <view class="time">{{ item.time | fromtTime }}</view>
              </view>
            </view>
            <view class="userRight">
              <text class="count">{{ item.likedCount }}</text>
              <text class="iconfont icon-dianzan iconDz"></text>
            </view>
          </view>
          <view class="newComment">{{ item.content }}</view>
        </view>
      </view>
    </view>
    <!-- 下载分享 -->
    <view class="share"> 分享音乐</view>
  </view>
</template>

<script>
import moment from "moment";
export default {
  onLoad(option) {
    this.getUrl(option.id); //获取播放地址
    this.getDetail(option.id); //获取歌曲详情
    this.getSimiSong(option.id); //获取相似歌曲
    this.getComment(option.id); //获取评论
    this.getLyric(option.id); //获取歌词
    this.onEndedMusic(); //监听音乐播放结束播放下一首
    uni.showLoading({
      title: "拼命加载中...",
    });
    setTimeout(() => {
      this.creatBgAudio();
      uni.hideLoading();
    }, 2000);
  },
  //监听分享
  onShareAppMessage(res) {
    console.log(res.from);
    if (res.from === "button") {
      // 来自页面内分享按钮
    }
    return {
      title: "燚淼音乐",
      path: "/pages/index/index",
    };
  },
  data() {
    return {
      paly: true, //监听播放
      bgAudio: "", //背景音频实例
      lrcObject: "", //保存歌词及时间对象
      currentTiem: "", //当前播放时间
      lyricIndex: 0, //当前歌词索引
      scrollindex: 0,
    };
  },
  computed: {
    //播放地址
    musicUrl() {
      return this.$store.state.currentMusicUrl;
    },
    //歌曲详情
    MusicDet() {
      return this.$store.state.currentMusicDet;
    },
    // 相似歌曲
    MusicSimilar() {
      return this.$store.state.currentMusicSimilar;
    },
    //精彩评论
    MusicComment() {
      return this.$store.state.currentMusicComment;
    },
  },
  filters: {
    //过滤评论时间
    fromtTime(val) {
      return moment(val).format("YYYY年MM月DD日hh:mm:ss");
    },
  },
  methods: {
    // 暂停播放
    isPalyC() {
      if (this.paly) {
        this.bgAudio.pause();
      } else {
        this.bgAudio.play();
      }
      this.paly = !this.paly;
      this.$store.commit("changePlay", this.paly);
    },
    // 获取播放地址
    getUrl(id) {
      this.request("/song/url", "GET", { id }).then((res) => {
        this.$store.commit("changeCurrentMusicUrl", res.data[0].url);
      });
    },
    //获取歌曲详情
    getDetail(ids) {
      this.request("/song/detail", "GET", { ids }).then((res) => {
        let obj = {};
        obj.title = res.songs[0].name; //歌名
        obj.singer = res.songs[0].ar[0].name; //歌手
        obj.coverImgUrl = res.songs[0].al.picUrl; //图片
        this.$store.commit("changeCurrentMusicDet", obj);
      });
    },
    //获取相似歌曲
    getSimiSong(id) {
      this.scrollindex = 0;
      this.lyricIndex = 0;
      this.request("/simi/song", "GET", { id }).then((res) => {
        this.$store.commit("changeCurrentMusicSimilar", res.songs);
      });
    },
    //获取精彩评论
    getComment(id) {
      this.request("/comment/music", "GET", {
        id: id,
        limit: 10,
        offset: 1,
      }).then((res) => {
        this.$store.commit("changeCurrentMusicCommentr", res.comments);
      });
    },

    //创建背景音乐实例
    creatBgAudio() {
      const bgAudioMannager = uni.getBackgroundAudioManager();
      this.scrollindex = 0;
      this.lyricIndex = 0;
      bgAudioMannager.title = this.$store.state.currentMusicDet.title;
      bgAudioMannager.singer = this.$store.state.currentMusicDet.singer;
      bgAudioMannager.coverImgUrl = this.$store.state.currentMusicDet.coverImgUrl;
      bgAudioMannager.src = this.$store.state.currentMusicUrl;
      setTimeout(() => {
        this.bgAudio = bgAudioMannager;
      }, 800);

      this.watchBgAudio(bgAudioMannager); //监听音乐播放和暂停
    },
    //监听音乐播放和暂停
    watchBgAudio(bgAudioMannager) {
      // 监听播放
      bgAudioMannager.onPlay(() => {
        this.paly = true;
        this.$store.commit("changePlay", this.paly);
      });
      // 监听暂停
      bgAudioMannager.onPause(() => {
        this.paly = false;
        this.$store.commit("changePlay", this.paly);
      });
      // 监听当前时间
      bgAudioMannager.onTimeUpdate(() => {
        let time = bgAudioMannager.currentTime;
        this.getDuration(time);
      });
    },
    //播放相似歌曲
    playSimilarMusic(item) {
      this.getUrl(item.id); //获取播放地址
      this.getDetail(item.id); //获取歌曲详情
      this.getSimiSong(item.id); //获取相似歌曲
      this.getComment(item.id); //获取评论
      this.getLyric(item.id); //获取歌词

      setTimeout(() => {
        this.creatBgAudio();
        uni.hideLoading();
        uni.setNavigationBarTitle({
          title: this.$store.state.currentMusicDet.title,
        });
      }, 2000);
    },
    //监听音乐播放结束播放下一首
    onEndedMusic() {
      const bgAudioMannager = uni.getBackgroundAudioManager();
      bgAudioMannager.onEnded(() => {
        let indexC = this.$store.state.currentIndex;
        if (indexC == this.$store.state.palyList.length - 1) {
          indexC = 0;
        } else {
          indexC++;
        }
        this.$store.commit("changeCurrentIndex", indexC);
        let newItem = this.$store.state.palyList[indexC];
        if (
          this.$store.state.palyList.length < 9 ||
          this.$store.state.palyList.length > 31 ||
          this.$store.state.palyList.length == 20
        ) {
          //歌曲列表小于10说明是相似歌曲的列表
          this.getUrl(newItem.id); //获取播放地址
          this.getDetail(newItem.id); //获取歌曲详情
          this.getSimiSong(newItem.id); //获取相似歌曲
          this.getComment(newItem.id); //获取评论
          this.getLyric(newItem.id); //获取歌词
        } else {
          //巅峰榜的歌曲列表
          this.getUrl(newItem.songs[0].id); //获取播放地址
          this.getDetail(newItem.songs[0].id); //获取歌曲详情
          this.getSimiSong(newItem.songs[0].id); //获取相似歌曲
          this.getComment(newItem.songs[0].id); //获取评论
          this.getLyric(newItem.songs[0].id); //获取歌词
        }

        setTimeout(() => {
          this.scrollindex = 0;
          this.lyricIndex = 0;
          this.creatBgAudio();
          uni.hideLoading();
          uni.setNavigationBarTitle({
            title: this.$store.state.currentMusicDet.title,
          });
        }, 2000);
      });
    },
    //相似音乐一键收听
    allListen() {
      this.$store.commit(
        "changePalyList",
        this.$store.state.currentMusicSimilar
      );

      this.$store.commit("changeCurrentIndex", 0);
      let newItem = this.$store.state.palyList[0];
      this.getUrl(newItem.id); //获取播放地址
      this.getDetail(newItem.id); //获取歌曲详情
      this.getSimiSong(newItem.id); //获取相似歌曲
      this.getComment(newItem.id); //获取评论
      this.getLyric(newItem.id); //获取歌词
      setTimeout(() => {
        this.creatBgAudio();
        uni.hideLoading();
        uni.setNavigationBarTitle({
          title: this.$store.state.currentMusicDet.title,
        });
      }, 2000);
    },
    //获取歌词
    getLyric(id) {
      this.request("/lyric", "GET", { id }).then((res) => {
        this.createLrcObj(res.lrc.lyric);
        this.lrcss = res.lrc.lyric;
      });
    },
    //解析歌词
    createLrcObj(lrc) {
      var oLRC = {
        ms: [], //歌词数组{t:时间,c:歌词}
      };
      if (lrc.length == 0) return;
      var lrcs = lrc.split("\n"); //用回车拆分成数组 (每一句歌词都用换行隔开了)
      for (var i in lrcs) {
        //遍历歌词数组
        lrcs[i] = lrcs[i].replace(/(^\s*)|(\s*$)/g, ""); //去除前后空格
        var arr = lrcs[i].match(/\[(\d+:.+?)\]/g); //提取时间字段，可能有多个
        var start = 0;
        for (var k in arr) {
          start += arr[k].length; //计算歌词位置 长度叠加
        }
        var content = lrcs[i].substring(start); //获取歌词内容 相当于减去时间字符串的长度剩下的就是内容
        for (var k in arr) {
          var t = arr[k].substring(1, arr[k].length - 1); //取[]间的内容
          // var t = arr[k]
          var s = t.split(":"); //分离:前后文字 便于计算成毫秒数
          oLRC.ms.push({
            //对象{t:时间,c:歌词}加入ms数组
            // t: t,
            t: (parseFloat(s[0]) * 60 + parseFloat(s[1])).toFixed(3),
            c: content === "" ? ".............." : content,
          });
        }
      }
      oLRC.ms.sort(function (a, b) {
        //按时间顺序排序
        return a.t - b.t;
      });
      this.lrcObject = oLRC.ms;
    },
    //当前播放位置
    getDuration(time) {
      for (let i = 0; i < this.lrcObject.length; i++) {
        //这里使用小于符号判断是为了 保证回退音乐进度事件的效果实现性
        if (time <= parseFloat(this.lrcObject[i].t)) {
          if (this.lyricIndex === i - 1) {
            break;
          }
          //找到比当前时间点 大一点的后一位的歌词的索引值
          this.lyricIndex = i - 1;
          this.scrollindex = this.scrollindex + 10;
          break;
        }
      }
    },
  },
};
</script>

<style lang="less">
// 光碟旋转
.rotate {
  animation: Anrotate 6s infinite linear;
}
@keyframes Anrotate {
  0% {
    transform: rotateZ(0deg);
  }
  100% {
    transform: rotateZ(360deg);
  }
}
.playDet {
  width: 100%;
  position: relative;
  .bgImg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    // background-size: 100% 100%;
    background-repeat: no-repeat;
    filter: blur(10px);
  }
  .bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .Bar {
    z-index: 1;
    transform-origin: left top;
    transform: rotateZ(0deg);
    position: relative;
    left: 305rpx;
    top: -50rpx;
    width: 365rpx;
    height: 275rpx;
    transition: all 1s;
    image {
      width: 100%;
      height: 100%;
    }
  }
  // 改变播放杆的状态
  .playBar {
    transform: rotateZ(30deg);
  }

  .CD {
    position: relative;
    width: 100%;
    height: 500rpx;
    // 播放
    .play {
      color: #fff;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      font-size: 126rpx;
    }
    //暂停
    .pause {
      color: #fff;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      font-size: 126rpx;
    }
    .disc {
      position: absolute;
      width: 500rpx;
      height: 500rpx;
      left: 50%;
      top: 50%;
      margin-left: -250rpx;
      margin-top: -250rpx;
    }
    .img {
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -140rpx;
      margin-top: -140rpx;
      width: 281rpx;
      height: 281rpx;
      border-radius: 50%;
    }
  }
  // 歌词
  .lyric {
    width: 100%;
    height: 365rpx;
    .scroll {
      text-align: center;
      width: 100%;
      height: 100%;
      overflow: auto;
      margin-top: 17rpx;
      transition: scrollTop 0.3s;
    }
  }
  //相似歌曲
  .similarSong {
    width: 720rpx;
    margin: 0 auto;
    margin-top: 50rpx;
    position: relative;
    z-index: 2;
    .similarTop {
      width: 100%;
      height: 100rpx;

      .topLeft {
        font-size: 40rpx;
        color: #fff;
      }
      .topRight {
        width: 180rpx;
        border-radius: 22rpx;
        height: 30px;
        line-height: 60rpx;
        border: 2rpx solid #fff;
        color: #fff;
        font-size: 20rpx;
        text-align: center;
      }
    }
    .similarList {
      width: 100%;
      .similarItem {
        width: 100%;
        // height: 170rpx;
        min-height: 170rpx;
        .ItemLeft {
          .similarImg {
            width: 100rpx;
            height: 100rpx;
            border-radius: 12rpx;
          }
          .songAndname {
            margin-left: 30rpx;
            .song {
              color: #fff;
              font-size: 40rpx;
            }
            .name {
              color: #a0a0a0;
              font-size: 30rpx;
            }
          }
        }
        .rightIcon {
          margin-right: 10rpx;
          font-size: 80rpx;
          color: #999;
        }
      }
    }
  }
  //精彩评论
  .comment {
    position: relative;
    width: 720rpx;
    margin: 0 auto;
    margin-top: 70rpx;
    .commTop {
      font-weight: 600;
      font-size: 40rpx;
      color: #fff;
    }
    .commentList {
      width: 100%;
      .commentItem {
        margin-top: 40rpx;
        border-bottom: 2rpx #ccc solid;
        width: 100%;
        // height: 180rpx;
        min-height: 180rpx;
        .user {
          .userLeft {
            image {
              width: 80rpx;
              height: 80rpx;
              border-radius: 50%;
            }
            .nameAndTime {
              margin-left: 13rpx;
              .name {
                color: #999;
                font-size: 26rpx;
              }
              .time {
                color: #a0a0a0;
                font-size: 20rpx;
              }
            }
          }
          .userRight {
            color: #999;
            .count {
              font-size: 20rpx;
            }
            .iconDz {
              font-size: 40rpx;
              margin-left: 12rpx;
            }
          }
        }
        .newComment {
          margin-left: 82rpx;
          font-size: 33rpx;
          color: #fff;
        }
      }
    }
  }
  //分享音乐
  .share {
    width: 720rpx;
    height: 60rpx;
    border-radius: 20rpx;
    margin: 0 auto;
    color: #fff;
    line-height: 60rpx;
    text-align: center;
    font-size: 30rpx;
    background: rgba(61, 27, 211, 0.6);
  }
}
</style>